#include <iostream>
#include <string>
#include <jsoncpp/json/json.h>
#include <memory>
#include <unistd.h>
#include <sstream>
bool serialize(const Json::Value &val, std::string &body)
{
    std::stringstream ss;
    Json::StreamWriterBuilder swb;
    swb["emitUTF8"] = true;
    std::unique_ptr<Json::StreamWriter> sw(swb.newStreamWriter());
    int ret = sw->write(val, &ss);
    body = ss.str();

    return true;
}
bool unserialize(const std::string &body, Json::Value &val)
{
    Json::CharReaderBuilder crb;
    std::unique_ptr<Json::CharReader> cr(crb.newCharReader());
    std::string errnos;
    bool ret = cr->parse(body.c_str(), body.c_str() + body.size(), &val, &errnos);
    if (ret == false)
    {
        std::cerr << "json unserialize fail" << std::endl;
        return false;
    }
    return true;
}
int main()
{
    const char *name = "小明";
    int age = 18;
    const char *sex = "男";
    float score[3] = {89, 90, 75};

    Json::Value student;
    student["姓名"] = name;
    student["年龄"] = age;
    student["性别"] = sex;

    for (int i = 0; i < 3; i++)
    {
        student["成绩"].append(score[i]);
    }
    Json::Value fav;
    fav["书籍"] = "西游记";
    fav["运动"] = "打篮球";

    student["爱好"] = fav;
    std::string body;
    serialize(student, body);
    std::cout << body << std::endl;
    std::string str = R"({"姓名":"小黑","年龄":19,"成绩":[32,45,56]})";
    Json::Value stu;
    bool ret = unserialize(str, stu);
    if (ret == false)
    {
        std::cerr << "unseralize error" << std::endl;
    }
    std::cout << stu["姓名"].asCString() << " " << stu["年龄"].asInt() << " " << std::endl;
    int size = stu["成绩"].size();
    for (int i = 0; i < size; i++)
    {
        std::cout << stu["成绩"][i].asInt() << std::endl;
    }
    return 0;
}